//
//  LBWComposePictureView.swift
//  weibo
//
//  Created by Limonwei on 15/12/14.
//  Copyright © 2015年 heima. All rights reserved.
//
//发布微博的配图视图部分

import UIKit

//Cell的可重用标示符
private let LBWComposePictureViewCellId = "LBWComposePictureViewCellId"

class LBWComposePictureView: UICollectionView {
    
    //定义一个增加图片的闭包
    var addImageClosure: (()->())?
    
    //记录一下图片  图片放入到数组中记录
    lazy var images: [UIImage] = [UIImage]()
    
    //初始化控件
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        //注册cell
        registerClass(LBWComposePictureViewCell.self, forCellWithReuseIdentifier: LBWComposePictureViewCellId)
        
        //设置数据源 代理
        delegate = self
        dataSource = self
        
        //添加控件
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置视图
    private func setupUI(){
        //放置图片的视图默认隐藏
        hidden = true
    }
    
    //定义一个供外界访问的方法
    func addImage(image: UIImage){
        
        images.append(image)
        //刷新数据
        reloadData()
        
        hidden = false
        
    }
    
    //在layoutSubView里计算每个item条目的frame
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //计算item的大小
         let layout = collectionViewLayout as! UICollectionViewFlowLayout
        //计算每个item的间隔
        let itemMargin: CGFloat = 5
        
        //计算宽高
        let itemSizeWH = CGFloat(Int(width - itemMargin * 2) / 3)
        layout.itemSize = CGSize(width: itemSizeWH, height: itemSizeWH)
        
        //设置水平垂直方向的间距
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        
        
    }
}

//数据源 代理 方法
extension LBWComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //如果是0张图片或者9张图片,就返回image.count 否则就返回image.count + 1
        let count = images.count
        
        return (count == 0 || count == 9) ? count : count + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LBWComposePictureViewCellId, forIndexPath: indexPath) as! LBWComposePictureViewCell
        
        if indexPath.row == images.count {
            //设置加号按钮
            cell.image = nil
        }else{
            cell.image = images[indexPath.row]
        }
        
        cell.indexPath = indexPath
        
        cell.deleteButtonClickClosure = { [weak self] (indexPath: NSIndexPath)->() in
            //移除图片
            self?.images.removeAtIndex(indexPath.row)
            
            //刷新数据
            self?.reloadData()
            
            self?.hidden = self?.images.count == 0

        }
        
        return cell
        
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //让对应的cell取消选中
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        if indexPath.row == images.count {
            //执行添加方法
            addImageClosure?()
        }
    }
}


//自定义collectionViewCell
class LBWComposePictureViewCell: UICollectionViewCell {
    //删除按钮点击执行的闭包
    var deleteButtonClickClosure: ((indexPath: NSIndexPath)->())?
    // 记录当前 cell 是在 collectionView 里面哪个位置,以便在移除图片的时候,知道要移除哪一张图片
    var indexPath: NSIndexPath?
    
    //其内容显示的图片
    var image: UIImage?{
        didSet{
            if image == nil {
                // 当 image 为 nil, 是代表外界让其设置成加号按钮
                imageView.image = UIImage(named: "compose_pic_add")
                
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            }else {
                
                //去掉高亮的图片
                imageView.image = image
                imageView.highlightedImage = nil
                
            }
            
            //根据是否有设置图片显示删除按钮
            deleteButton.hidden = image == nil
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        //添加控件
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        //添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(contentView)
            make.top.equalTo(contentView)
        }
    }
    
    
    
    //懒加载控件
    //懒加载一个图片视图
    private lazy var imageView: UIImageView = UIImageView()
    
    //懒加载删除按钮
    private lazy var deleteButton: UIButton = {
       
        let button = UIButton()
        
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: .TouchUpInside)
        
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        
        return button
        
    }()
    
    //实现删除按钮的点击事件
    @objc private func deleteButtonClick(){
        
        deleteButtonClickClosure?(indexPath: indexPath!)
    }
    
}



















